import tensorflow
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
import numpy as np
from self_mudle import plot_learning_curves

(train_x, train_y), (test_x, test_y)  = keras.datasets.fashion_mnist.load_data()
valid_x, valid_y = train_x[:5000], train_y[:5000]
train_x, train_y = train_x[5000:], train_y[5000:]

# 标准化 ： 又叫均值方差归一化  计算均值方差 调整数据到服从标准正态分布
# fit计算均值和方差 transform调整数据 验证集和测试集调整时都用训练集的均值和方差
# train_x的数据是[0,288]的uint8数据 要做除法 先转换成np.float32
# transform()要传入二维矩阵 train_x是[batch_size,28,28] 因此先reshape
scaler = StandardScaler()
train_x = scaler.fit_transform(train_x.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
valid_x = scaler.transform(valid_x.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
test_x = scaler.transform(test_x.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)

model = keras.Sequential([
    keras.layers.Flatten(),
    keras.layers.Dense(300,activation='relu'),
    keras.layers.Dense(200,activation='relu'),
    keras.layers.Dense(10,activation='softmax')
])

# layers中加input_shape不用写None   模型build中加input_shape要写None
# build一般是搭配子类API使用
model.build(input_shape=[None,28,28])
model.summary()

model.compile(  
    optimizer = keras.optimizers.SGD(0.001),
    loss = 'sparse_categorical_crossentropy',  # 标签用的数字：sparse_categorical_crossentrpy
                                               # 标签用的one-hot: categorical_crossentrpy
    metrics = ['accuracy']  # 不添加accuracy 在fit过程中只关注loss
)

history = model.fit(train_x,train_y,epochs=3,validation_data=(valid_x,valid_y))

predict = model.evaluate(test_x, test_y)

plot_learning_curves.plot_learning_curves(history)